import json

from django.http import HttpResponseForbidden
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection

from apps.goods.models import SKU
from utils.cookiesecret import CookieSecret

#购物车功能
class CartsView(View):

    #添加购物车
    def post(self,request):
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected',True)

        #判断参数是否齐全
        if not all([sku_id,count]):
            return HttpResponseForbidden('缺少必传参数')
        #判断sku_id是否存在
        try:
            sku = SKU.objects.get(id = sku_id)
        except Exception as e:
            return HttpResponseForbidden('商品不存在')
        #判断count是否为数字
        try:
            count = int(count)
        except Exception as e:
            return HttpResponseForbidden('参数count有误')
        #判断select是否为bool值
        if selected:
            if not isinstance(selected,bool):
                return HttpResponseForbidden('参数selected有误')

        #判断用户是否登录
        user = request.user
        if user.is_authenticated:
            #登录用户使用redis存储
            carts_redis_client = get_redis_connection('carts')
            client_data = carts_redis_client.hgetall(user.id)
            if not client_data:
                carts_redis_client.hset(user.id,sku_id,json.dumps({'count':count,'selected':selected}))
            #数据库中存在用户的数据条，判断商品是否添加过购物车
            if str(sku_id).encode() in client_data:
                #添加过购物车，修改count
                child_dict = json.loads((client_data[str(sku_id).encode()]).decode())
                child_dict['count'] += count
                carts_redis_client.hset(user.id,sku_id,json.dumps(child_dict))
            else:
                #未添加过购物车，新增属性
                carts_redis_client.hset(user.id,sku_id,json.dumps({'count':count,'selected':selected}))
            return JsonResponse({'code':'0','errmsg':'添加购物车成功'})

        else:
            #未登录用户使用cookie存储
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = CookieSecret.loads(cart_str)
            else:
                cart_dict = {}

            if sku_id in cart_dict:
                origin_count = cart_dict[sku_id]['count']
                count += origin_count
            cart_dict[sku_id] = {
                'count':count,
                'selected':selected
            }
            cookie_cart_str = CookieSecret.dumps(cart_dict)

            response = JsonResponse({'code':'0','errmsg':'添加购物车成功'})

            response.set_cookie('carts',cookie_cart_str,max_age=24*30*3600)
            return response

    #展示购物车
    def get(self,request):
        #判断用户是否登录
        user = request.user
        if user.is_authenticated:
            #从redis中读取数据
            carts_redis_data = get_redis_connection('carts')
            carts_data = carts_redis_data.hgetall(user.id)
            carts_dict = {}
            for data in carts_data.items():
                print(data,data[1])
                carts_dict[int(data[0])] = json.loads(data[1].decode())

        else:
            #从cookie中读取数据
            cookie_str = request.COOKIES.get('carts')
            if cookie_str:
                carts_dict = CookieSecret.loads(cookie_str)
            else:
                carts_dict = {}

        sku_ids = carts_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        cart_skus = []
        for sku in skus:
            cart_skus.append({
                'id':sku.id,
                'name':sku.name,
                'count':carts_dict.get(sku.id).get('count'),
                'selected':str(carts_dict.get(sku.id).get('selected')),
                'default_image_url':sku.default_image.url,
                'price':str(sku.price),
                'amount':str(sku.price*carts_dict.get(sku.id).get('count')),
            })
        context = {
            'cart_skus':cart_skus,
        }

        return render(request,'cart.html',context)

    #修改
    def put(self,request):
        #接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict['sku_id']
        count = json_dict['count']
        selected = json_dict.get('selected',True)

        #校验
        if not all([sku_id,count]):
            return HttpResponseForbidden('缺少必传参数')
        #判断sku_id 是否存在
        try:
            sku = SKU.objects.get(id = sku_id)
        except:
            return HttpResponseForbidden('商品不存在')
        #判断count是否为数字
        try:
            count = int(count)
        except:
            return HttpResponseForbidden('count参数错误')
        #判断selected是否为bool
        if selected:
            if not isinstance(selected,bool):
                return HttpResponseForbidden('selected参数错误')

        #判断用户是否登录
        user = request.user
        if user.is_authenticated:
            #redis
            carts_redis_client = get_redis_connection('carts')
            new_data = {'count':count,'selected':selected}
            carts_redis_client.hset(user.id,sku_id,json.dumps(new_data))
        else:
            #cookie
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = CookieSecret.loads(cart_str)
            else:
                cart_dict = {}
            cart_dict[sku_id] = {
                'count':count,
                'selected':selected
            }
            cookie_cart_str = CookieSecret.dumps(cart_dict)
        #构建前端数据
        cart_sku = {
            'id':sku_id,
            'count': count,
            'selected': selected,
            'name': sku.name,
            'default_image_url': sku.default_image.url,
            'price': sku.price,
            'amount': sku.price * count,
        }
        response = JsonResponse({'code':0,'errmsg':'修改购物车成功','cart_sku':cart_sku})
        if not user.is_authenticated:
            response.set_cookie('carts',cookie_cart_str,max_age=24 * 30 * 3600)
        return response

    #删除
    def delete(self,request):
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')

        # 判断sku_id是否存在
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return HttpResponseForbidden('商品不存在')

        # 判断用户是否登录
        user = request.user
        if user is not None and user.is_authenticated:
            # 用户未登录，删除redis购物车
            carts_redis_client = get_redis_connection('carts')

            # 根据用户id 删除商品sku
            carts_redis_client.hdel(user.id, sku_id)

            # 删除结束后，没有响应的数据，只需要响应状态码即可
            return JsonResponse({'code': 0, 'errmsg': '删除购物车成功'})
        else:
            # 用户未登录，删除cookie购物车
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                # 转成明文
                cart_dict = CookieSecret.loads(cart_str)
            else:
                cart_dict = {}

            # 创建响应对象
            response = JsonResponse({'code': 0, 'errmsg': '删除购物车成功'})
            if sku_id in cart_dict:
                # 删除数据
                del cart_dict[sku_id]
                # 将字典转成密文
                cookie_cart_str = CookieSecret.dumps(cart_dict)
                # 响应结果并将购物车数据写入到cookie
                response.set_cookie('carts', cookie_cart_str, max_age=24 * 30 * 3600)
            return response


#全选功能
class CartsSelectAllView(View):
    def put(self,request):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        selected = json_dict.get('selected', True)

        # 校验参数
        if selected:
            if not isinstance(selected, bool):
                return HttpResponseForbidden('参数selected有误')

        # 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 用户已登录，操作redis购物车
            carts_redis_client = get_redis_connection('carts')
            carts_data = carts_redis_client.hgetall(user.id)

            # 将所有商品 改成True
            for carts in carts_data.items():
                sku_id = carts[0].decode()
                carts_dict = json.loads(carts[1].decode())
                if selected:
                    # 全选
                    carts_dict['selected'] = True
                else:
                    # 取消全选
                    carts_dict['selected'] = False

                carts_redis_client.hset(user.id, sku_id, json.dumps(carts_dict))

            return JsonResponse({'code': 0, 'errmsg': '全选购物车成功'})
        else:
            # 用户未登录，操作cookie购物车
            carts_str = request.COOKIES.get('carts')
            response = JsonResponse({'code': 0, 'errmsg': '全选购物车成功'})
            if carts_str is not None:
                carts_dict = CookieSecret.loads(carts_str)
                for sku_id in carts_dict:
                    carts_dict[sku_id]['selected'] = selected
                cookie_cart = CookieSecret.dumps(carts_dict)
                response.set_cookie('carts', cookie_cart, 24 * 30 * 3600)

            return response



